#include <iostream>
using namespace std;

struct PolyNode {
    int coef;
    int exp;
    PolyNode *next;
};

PolyNode* polyMultiply(PolyNode *p1, PolyNode *p2) {
    PolyNode *result = new PolyNode();
    PolyNode *p = p2;
    while (p1 != NULL) {
        p = p2;
        while (p != NULL) {
            int coef = p1->coef * p->coef;
            int exp = p1->exp + p->exp;
            PolyNode *q = result;
            while (q->next != NULL && q->next->exp > exp) {
                q = q->next;
            }
            if (q->next != NULL && q->next->exp == exp) {
                q->next->coef += coef;
            }
            else {
                PolyNode *newNode = new PolyNode();
                newNode->coef = coef;
                newNode->exp = exp;
                newNode->next = q->next;
                q->next = newNode;
            }
            p = p->next;
        }
        p1 = p1->next;
    }
    return result->next;
}

void printPoly(PolyNode *p) {
    if (p == NULL) {
        cout << "0 0" << endl;
        return;
    }
    while (p != NULL) {
        cout << p->coef << " " << p->exp << " ";
        p = p->next;
    }
    cout << endl;
}

int main() {
    PolyNode *p1 = new PolyNode();
    PolyNode *p1_1 = new PolyNode();
    PolyNode *p1_2 = new PolyNode();
    p1->coef = 3;
    p1->exp = 2;
    p1->next = p1_1;
    p1_1->coef = 1;
    p1_1->exp = 1;
    p1_1->next = p1_2;
    p1_2->coef = 2;
    p1_2->exp = 0;
    p1_2->next = NULL;
    PolyNode *p2 = new PolyNode();
    PolyNode *p2_1 = new PolyNode();
    PolyNode *p2_2 = new PolyNode();
    p2->coef = 4;
    p2->exp = 1;
    p2->next = p2_1;
    p2_1->coef = 1;
    p2_1->exp = 0;
    p2_1->next = p2_2;
    p2_2->coef = 3;
    p2_2->exp = 2;
    p2_2->next = NULL;
    cout << "p1: ";
    printPoly(p1);
    cout << "p2: ";
    printPoly(p2);
    PolyNode *result = polyMultiply(p1, p2);
    cout << "result: ";
    printPoly(result);
    return 0;
}